import React from "react";

import { ajax,isNull} from '../../common';

import {Badge,Select,Spin} from 'antd';

import UIIcon from '../../uicomponents/UIIcon';

const Option = Select.Option;

/** 
 * 产品模型对象选择
*/
export default class ProductModelObjectSelect extends React.Component {

	constructor(props) {
		super(props);
	}

	state = {
		data: [],
		value: [],
		fetching: false,
	}

	renderModelPackage = (modelPackage) => {
		let color = "processing";
		if ('IN_USE' === modelPackage.status) {
			color = 'processing'
		}
		else if ('CLOSED' === modelPackage.status) {
			color = 'error'
		}

		return (<Badge status={color} style={{ marginLeft: 6 }} text={<span><UIIcon icon='folder' />{modelPackage.packageName}</span>} />)
	}

	handleSelect = (value, opt) => {
		if (this.props.onSelectModelObject) {
			this.props.onSelectModelObject(value);
		}
	}

	fetchModelObject = (value) => {
		
		this.setState({ data: [], fetching: true });
		ajax('PRODUCT/MODEL/productModelObject/queryModelObjects',{objectName : value,domainId : this.props.domainId,objectType : this.props.objectType},(result) =>{
			const data = result.records.map(modelObject => ({
				text: `${modelObject.packageName}.${modelObject.objectName}`,
				value: modelObject.id,
			}));

			this.setState({ data, fetching: false });
		});
	}

	handleChange = (value) => {
		this.setState({
		  value,
		  data: [],
		  fetching: false,
		});
	}

	render() {

		const { fetching, data, value } = this.state;

		return (
			<Select
				showSearch
				labelInValue
				value={value}
				placeholder="选择模型对象"
				notFoundContent={fetching ? <Spin size="small" /> : null}
				showArrow={false}
				filterOption={false}
				onSearch={this.fetchModelObject}
				onChange={this.handleChange}
				onSelect={this.handleSelect}
				style={{width : isNull(this.props.width) ? '400px' : this.props.width}}
			>
				{data.map(d => <Option key={d.value}>{d.text}</Option>)}
			</Select>
		);
	}
}
